#!usr/bin/env python
# -*- coding: utf-8 -*-
import json
import datetime
from fx.common.base_redis import rdb
from fx.common.redis_keys import REDIS_KEY_PREFIX
from fx.lib.utils import FancyDict


class BaseRedisModel(object):
    dict_default_columns = []

    save_key = None

    def to_dict(self, columns=None):
        dct = FancyDict()
        if columns is None:
            columns = self.dict_default_columns
        for col in columns:
            value = getattr(self, col)
            if isinstance(value, datetime.datetime):
                value = value.strftime('%Y-%m-%d %H:%M:%S')
            dct[col] = value
        return dct

    def save(self, columns=None):
        if self.save_key:
            save_value = json.dumps(self.to_dict(columns=columns))
            rdb.set(self.save_key, save_value)

    def get_data(self, columns=None):
        r_data = rdb.get(self.save_key)
        if r_data:
            data_dict = json.loads(r_data)
            if columns is None:
                columns = self.dict_default_columns
            for col in columns:
                value = data_dict.get(col, None)
                setattr(self, col, value)
            return self
        return None

    def delete(self):
        if self.save_key:
            rdb.delete(self.save_key)


class ShareModel(BaseRedisModel):
    save_key = REDIS_KEY_PREFIX.format(key='share_info')
    dict_default_columns = ['wx_qr_code', 'wb_link']

    wx_qr_code = None
    wb_link = None
